package nina.yiyou.paystub.output

import nina.yiyou.paystub.input.TableMetaReader

import javax.imageio.ImageIO
import java.awt.Image
import java.awt.image.RenderedImage
import java.nio.file.Files
import java.nio.file.Path

class PaystubResultGenerator {

  PaystubResultGenerator(Image tableImg, TableMetaReader.Meta tableMeta, Path resultExcel) {
    _tableImg = tableImg
    _tableMeta = tableMeta
    _resultExcel = resultExcel
  }

  void generate() {
    String excelFullName = _resultExcel.getFileName().toString()
    String resultDirName = excelFullName.substring(0, excelFullName.lastIndexOf('.')) + '_工资单'

    Path resultDir = _resultExcel.resolveSibling(resultDirName)
    if (!Files.isDirectory(resultDir)) {
      Files.createDirectory(resultDir)
    }

    _tableMeta.rowList().parallelStream()
        .map { new Tuple2<>(it, makePaystubImage(it)) }
        .forEach { saveImage(it.first, it.second, resultDir) }
  }

  private RenderedImage makePaystubImage(TableMetaReader.Employee employee) {
    return new ResultImageMaker(employee, _tableImg, _tableMeta).make()
  }

  private void saveImage(TableMetaReader.Employee employee, RenderedImage image, Path resultDir) {
    String imgName = "${employee.name()}_${employee.id()}.png"
    Path imgPath = resultDir.resolve(imgName)

//    println('保存工资单：' + imgPath)
    ImageIO.write(image, 'png', imgPath.toFile())
  }

  private final Image _tableImg
  private final TableMetaReader.Meta _tableMeta

  private final Path _resultExcel
}
